//
//  PSSochiCalculator.m
//  PrefCore
//
//  Created by Sergey on 2/27/14.
//  Copyright (c) 2014 Play-on-smart. All rights reserved.
//

#import "PSSochiCalculator.h"

@implementation PSSochiCalculator

-(instancetype)init {
    if (self = [super initWithPassingScorer:[PSScorer passingScorer]
                           costsPlaySuccess:@[@2, @4,  @6,  @8, @10]
                              costsPlayFail:@[@2, @4,  @6,  @8, @10]
                          costsWhistSuccess:@[@2, @4,  @6,  @8, @10]
                             costsWhistFail:@[@2, @4,  @6,  @8, @10]
                        normalizationFactor:1]) {
    }
    return self;
}

-(void)writeToPoolOfPlayer:(PSPlayer*)player
                      game:(PSGame*)game
                  settings:(PSGameSettings*)settings
                     value:(PSScoreValue)value {
    PSScore *score = [game scoreForPlayerId:player.identifier];
    PSScoreValue remainingPoints = settings.poolSize - score.pool.current;
    PSScoreValue aid = MAX(value - remainingPoints, 0);
    value -= aid;
    // Add points to the player's pool
    [super writeToPoolOfPlayer:player game:game settings:settings value:value];
    // Check if we need to process aid; otherwise, exit
    if (!aid) {
        return;
    }
    // Do the American aid
    PSPlayer *p2 = [game nextPlayer:player];
    PSScorePool *p2pool = [game scoreForPlayerId:p2.identifier].pool;
    PSPlayer *p3 = [game nextPlayer:p2];
    PSScorePool *p3pool = [game scoreForPlayerId:p3.identifier].pool;
    NSArray *orderOfAid;
    if (p2pool.current >= p3pool.current) {
        orderOfAid = @[p2, p3];
    } else {
        orderOfAid = @[p3, p2];
    }
    // write whists ten times of played game
    for (PSPlayer *p in orderOfAid) {
        PSScorePool *pool = [game scoreForPlayerId:p.identifier].pool;
        PSScoreValue n = MIN(settings.poolSize - pool.current, aid);
        [pool addValue:n];
        [self writeWhistsFromPlayer:player toPlayer:p game:game value:10 * n];
        aid -= n;
    }
    // if aid still > 0, then reduce from mountain
    if (aid > 0) {
        PSScoreValue reduction = MIN(score.mountain.current, aid);
        [self writeToMountainOfPlayer:player game:game value:-reduction];
    }
}

@end
